package com.itheima.reggie.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.itheima.reggie.entity.OrderDetail;
import com.itheima.reggie.entity.Orders;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
import java.util.Random;
import java.util.UUID;

import static com.alipay.api.AlipayConstants.NOTIFY_URL;

@RestController
public class PayController {

    private final String APP_ID = "2021000121669305";
    private final String APP_PRIVATE_KEY = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC0nyuStQfcs9PeFQwKrXjy4DQa7S/4O0tSeQZEHOeAuHGXTA2TYJ6diKzKmK+Ai81eOk+EWj5rSMEMXqLNZV9J0NzncfoV5PygB4uFFf3m15Af3vGg4axyLyjh6BD/m6fUS+e1Rxx7anvaXr3WZcXyYOxQW8nC0f88yIkBTRm3PmlIwLH2UDxpKvzBm4KRTX0Sgm4VtUqk4a03dOk0SA5urgq/J+kS+7wDzDxJjeRezjMGzJuVfERW2BnW/sxWKxgUZf4vrxqsEIStuv+DK9e1OYa8z2UBQjw9G+01v1BhEYcN5jlP4zPtI1XefcXP8Pl2scaumD+cvquKPS9gIOvPAgMBAAECggEAZYmdSynts4p8LjqSvGXsukyDvidcciWTIFfcx+mf0uLdKHqenx0PzeuJh5LyBkeROcl57iN1N4Z8z+FbkC/Os4ZwyMNwHWLPCX90VWqZg23nHaONHi3/bWlJiEWXWLo+TMAnD+dcAZ1I5uefvKkV8D3AWyRedeDrpVXufwbC0BmYcIqIjHEbjvtxN56i/PxttDd0N2VymDybpGu1M541ABQOuxKvisL/aBMdSrPFm4ApxmbIePKN/mEPlsR8Cy4UnuYxfJtSdlRgln2ICiacWUEtleJWM7C816SRUq+Rnz+WbzzGaF8/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F6izWVfSdDc53H6FeT8oAeLhRX95teQH97xoOGsci8o4egQ/5un1EvntUcce2p72l691mXF8mDsUFvJwtH/PMiJAU0Ztz5pSMCx9lA8aSr8wZuCkU19EoJuFbVKpOGtN3TpNEgObq4KvyfpEvu8A8w8SY3kXs4zBsyblXxEVtgZ1v7MVisYFGX+L68arBCErbr/gyvXtTmGvM9lAUI8PRvtNb9QYRGHDeY5T+Mz7SNV3n3Fz/D5drHGrpg/nL6rij0vYCDrzwIDAQAB";
    //这是沙箱接口路径,正式路径为https://openapi.alipay.com/gateway.do
    private final String GATEWAY_URL ="https://openapi.alipaydev.com/gateway.do";
    private final String FORMAT = "JSON";
    //签名方式
    private final String SIGN_TYPE = "RSA2";
    //支付宝异步通知路径,付款完毕后会异步调用本项目的方法,必须为公网地址
    //private final String NOTIFY_URL = "http://公网地址/notifyUrl";
    //支付宝同步通知路径,也就是当付款完毕后跳转本项目的页面,可以不是公网地址
    private final String RETURN_URL = "http://localhost:8080/front/page/pay-success.html";

    @RequestMapping("/alipay")
    public void alipay(HttpServletResponse httpResponse, HttpSession session) throws IOException {

        Random r=new Random();
        //实例化客户端,填入所需参数
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //在公共参数中设置回跳和通知地址
        request.setReturnUrl(RETURN_URL);
        //request.setNotifyUrl(NOTIFY_URL);

        Orders order = (Orders) session.getAttribute("order");
        List<OrderDetail> list = (List<OrderDetail>) session.getAttribute("orderDetail");

        //商户订单号，商户网站订单系统中唯一订单号，必填
        //生成随机Id
        String out_trade_no = order.getId().toString();
        //付款金额，必填
        String total_amount =order.getAmount().toString();
        //订单名称，必填
        String subject ="请支付";
        //商品描述，可空
        String body = "";
        for (OrderDetail orderDetail : list) {
            if (orderDetail.getDishFlavor() != null) {
                body += "餐品名称" + orderDetail.getName() + "-----" + "口味" + orderDetail.getDishFlavor() + "-----" + "价格" + orderDetail.getAmount() + "     ";
            }else {
                body += "餐品名称" + orderDetail.getName() + "-----"+ "价格" + orderDetail.getAmount() + "     ";
            }
        }
        request.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }
}

